<template>
  <view class="wx-quickly-login">
    <button
      v-if="!agree"
      class="wx-quickly-login-btn"
      type="primary"
      @click="promptEject"
    >
      快捷登录
    </button>
    <button
      v-else
      class="wx-quickly-login-btn"
      type="primary"
      open-type="getPhoneNumber"
      @getphonenumber="getPhoneNumber"
    >
      快捷登录
    </button>
  </view>
</template>
<script setup>
import { ref, defineProps, getCurrentInstance, defineEmits } from "vue";
import { loginByQuicklyAPi, csHqAPi } from "@/api/login";
const props = defineProps({
  agree: {
    type: Boolean,
  },
});
const emit = defineEmits(["on-success"]);
// const shops_code = uni.getStorageSync("shops_code");
const { proxy } = getCurrentInstance();
const phoneCode = ref("");
// const userPhoneNumber = ref("");
const getPhoneNumber = async (e) => {
  console.log("e.detail.userInfo", e.detail.userInfo);

  if (e.detail?.code) {
    phoneCode.value = e.detail.code;
    getCode();
  }
};
function promptEject() {
  proxy.modal.msg("请阅读《用户服务协议》和《隐私政策》并勾选");
}

const code = ref("");
const getCode = async () => {
  // const  res = await csHqAPi()
  // console.log("csHqAPi",res);
  // alert(`csHqAPi",${res}`)
  uni.login({
    success(res) {
      code.value = res.code;
      loginByQuickly();
    },
  });
};

/**
 * 小程序手机号一键登录
 * @returns {Promise<void>}
 */
const loginByQuickly = async () => {
  await uni.showLoading({
    title: "登录中...",
  });
  const params = {
    client_id: "huatai",
    client_secret: "waytale",
    auth_type: "wx",
    code: code.value,
    phone_code: phoneCode.value,
    wx_login_type: "0",
    grant_type: "password",
    // username: userPhoneNumber.value
  };
  uni.setStorageSync("token", access_token);
  const res = await loginByQuicklyAPi(params);
  const { access_token } = res;
  await uni.showToast({
    title: "登录成功",
    duration: 2000,
  });
  setTimeout(async () => {
    if (access_token) {
      uni.hideLoading();
      uni.setStorageSync("token", access_token);
      emit("on-success", false);
    }
  }, 2000);
};
</script>
<style scoped lang=less>
.wx-quickly-login {
  width: 80vw;
  margin-top: 40rpx;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
  align-items: center;
  &-text {
    font-weight: 400;
    font-size: 23rpx;
    color: @color-origin-white;
  }
  &-btn {
    width: 80vw;
    margin-top: 29rpx;
    background-color: @color-green;
    background-repeat: no-repeat;
    font-family: "ali-p";
    font-size: @font-size-31;
    font-weight: 400;
    padding-left: 14rpx;
    padding-right: 14rpx;
    border: none;
  }
}

button::after {
  border: none;
}
</style>
